package com.hjs.community.inform.utils;

import com.alibaba.fastjson.JSON;

import com.community.common.core.corethreadPool.ExecutorUtils;
import com.community.common.core.utils.ApacheHttpUtils;
import com.hjs.community.inform.config.SmsProperties;
import com.hjs.community.inform.constant.RedisKey;
import com.hjs.community.inform.dto.SMSDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

// 发送短信的工具类
@Component
@Slf4j
public class SMSUtils {

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    private String sendPath = "/sms/send?mobile=%s&templateId=M105EABDEC&value=%s";

    private String statusPath = "/sms/send-status?mobile=%s&taskId=%s";

    public void send(SMSDto smsDto) {//ExecutorUtils

        ExecutorUtils.getThreadPoll().submit(()->{
            // 1.发送短信获取结果
            Map<String, Object> map = doSend(smsDto);

            Integer num = smsDto.getNum();
            if (num > 3) {
                log.debug("当前发送已发送3次，需要删除");
                redisTemplate.opsForSet().remove(RedisKey.SEND_SMS_ERROR_KEY, smsDto);
                return;
            }
            smsDto.setNum(++num);

            Integer code = (Integer) map.get("code");
            String taskId = (String) ((Map) map.get("data")).get("taskId");
//         2.判断短信是否发送成功
            if (code == 200) {
                log.debug("短信发送成功:{}", smsDto);
            } else {
                // 短信发送失败，失败后需要考虑重新发送
                // 把发送失败短信保存下来(reids-->)，启动一个定时任务再次放
                smsDto.setTaskId(taskId);
                redisTemplate.opsForSet().add(RedisKey.SEND_SMS_ERROR_KEY, smsDto);
            }
        });
    }

    private Map<String, Object> doSend(SMSDto smsDto) {

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + smsProperties.getAppcode());

        sendPath = String.format(sendPath, smsDto.getMobile(), smsDto.getCode());
        String json = ApacheHttpUtils.postJson(smsProperties.getHost() + sendPath, headers, null);
        log.debug("短信发送结果：{}", json);
        return JSON.parseObject(json, Map.class);
    }

    /**
     * true代表发送成功
     * false:代表发送失败
     *
     * @param taskId
     * @param mobile
     * @return
     */
    public Boolean query(String taskId, String mobile) {
        String path = String.format(statusPath, mobile, taskId);
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + smsProperties.getAppcode());

        String json = ApacheHttpUtils.getUrl(smsProperties.getHost() + path, headers);
        Map map = JSON.parseObject(json, Map.class);
        Integer code = (Integer) map.get("code");
        return code == 200; // ture
    }
}
